<template>
    <!--弹出窗-->
    <modal ref="modal_1"
           :title="title"
           :isCloseConfirm="this.editable"
           :fullscreen="this.fullscreen"
           top="3%"
           width="80%"
           :close-on-click-modal="true"
           @modalOpened="opened"
           @modalClose="closed">

        <avue-form :option="option" ref="form" v-model="form" @submit="onSubmit" >
            <template #cnItem>
                <cn-item ref="cnItem" @disabledCommit="disabledCommit" @disabledFiled="disabledFiled"></cn-item>
            </template>
        </avue-form>
        <!--底部按钮块, 默认只有"取消"按钮-->
        <template #footerButton>
            <el-button type="primary" v-if="(permission.cn_main_add || permission.cn_main_edit) && editable"
                       :disabled="btnLoading" @click="this.$refs.form.submit()">保存
            </el-button>
            <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
        </template>
    </modal>
</template>

<script>
    import { getList, getDetail, add, update, remove } from "@/api/anwise/logistics/cn_main";
    import { mapGetters } from "vuex";
    import { getDeptTree } from '@/api/system/dept';
    import website from '@/config/website';
    import {Pattern} from "@/utils/validate.js";
    import {dateFormat} from "@/utils/date.js";
    import cnItem from './cn_item.vue';

    export default {
        components: {
            cnItem,
        },
        data() {
            return {
                isEnglish:'1',
                hiddenPrice:'1',
                hasItem:false,
                box:false,
                emits: ["success"],
                editable: false,
                title: "CN信息",
                isCloseConfirm: false,
                fullscreen: false,
                btnLoading: false,
                customer:{
                    salesName:"",
                    remark:"",
                    salesRemark:"",
                },
                form: {},
                query: {},
                loading: true,
                option: {
                    card: true,
                    tabs: true,
                    tabsActive: 1,
                    height: 'auto',
                    calcHeight: 30,
                    labelWidth: 150,
                    menuWidth: 120,
                    submitBtn: false,
                    emptyBtn: false,
                    column: [
                        {
                            label: "CN编号",
                            prop: "cnNo",
                            type: "input",
                            disabled:true,
                            display:true,
                            span:8,
                            placeholder:'保存后自动生成编号',
                            rules: [{
                                required: false,
                                message: "请输入CN编号",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "出货时间",
                            prop: "loadingDate",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            span:8,
                            rules: [{
                                required: true,
                                message: "请选择出货时间",
                                trigger: "blur"
                            }],
                        },
                    ],
                    group: [
                        {
                            icon: 'el-icon-house',
                            label: 'CN项信息',
                            prop: 'group1',
                            column: [
                                {
                                    label: '',
                                    prop: 'cnItem',
                                    className: 'addPadding',
                                    span: 24,
                                    labelWidth: 0,
                                    formslot: true,
                                    display: true,
                                },
                            ],
                        },
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.cn_main_add, false),
                    viewBtn: this.validData(this.permission.cn_main_view, false),
                    delBtn: this.validData(this.permission.cn_main_delete, false),
                    editBtn: this.validData(this.permission.cn_main_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
        },
        methods: {
            disabledFiled(hasItem) {
                this.hasItem = hasItem;
            },
            changeDeliDate(value) {
                let cnItem = this.$refs.cnItem.$refs.tableRef.getTableData().fullData;
                if (cnItem.length > 0) {
                    cnItem.forEach(item => {
                        item.deliDate = value;
                    })
                }
            },
            disabledCommit(data) {
                this.btnLoading = data;
            },
            async validItemEvent() {
                const $table = this.$refs.cnItem.$refs.tableRef
                let errMap = undefined;
                await $table.validate().then((err) => {
                    console.log("err:",err)
                    errMap=err;
                })
                return errMap;
            },
            async onSubmit(form, done) {
                const $table = this.$refs.cnItem.$refs.tableRef
                let checkcnItem = false;
                const errMap = await this.validItemEvent();
                console.log(errMap);
                if (errMap) {
                    this.$message({
                        type: 'error',
                        message: 'CN项信息有误！',
                    });
                    checkcnItem = true;
                    done();
                    return;
                }

                console.log("checkcnItem",checkcnItem);
                if (!checkcnItem) {
                    this.btnLoading = true;
                    form.addList = $table.getInsertRecords();
                    form.updateList = $table.getUpdateRecords();
                    form.deleteList = $table.getRemoveRecords();
                    form.itemList = $table.getTableData().fullData;
                    if (!form.itemList || form.itemList.length < 1) {
                        this.$message({
                            type: 'error',
                            message: '无CN项信息！',
                        });
                        this.btnLoading = false;
                        done();
                        return;
                    }
                    console.log(form)
                    update(form).then(res => {
                        if (res.data.success) {
                            this.$message({
                                type: "success",
                                message: res.msg || "保存成功!"
                            });
                            setTimeout(() => {
                                this.btnLoading = false;
                                done();
                                this.$refs.modal_1.hide();
                            }, 1000)
                        } else {
                            this.$message({
                                type: "error",
                                message: res.msg || "保存失败!"
                            });
                        }
                    }).catch(err => {
                        console.log(err)
                        done();
                        this.btnLoading = false;
                    })

                }
            },
            show(option) {
                this.title = option.title;
                this.type = option.type;
                this.option.detail = this.type === "view";
                this.editable = this.type !== "view";
                if (option.id) {
                    this.hasItem=true;
                    console.log("option.id");
                    setTimeout(() => {
                        getDetail(option.id).then(res => {
                            if (res.data.success) {
                                this.form = res.data.data;
                                // this.customer.salesName =  this.form.customer.cartonMarkRemark;
                                // this.customer.remark = this.form.customer.prodRemark;
                                // this.customer.salesRemark = this.form.customer.salesRemark;
                                this.$refs.cnItem.setData(this.editable, this.form.cnNo)
                                this.$refs.cnItem.asnList = this.form.asnList;
                            }
                        })
                    }, 500);
                } else {
                    this.form = {}
                    this.form.cnDate = dateFormat(new Date(),"yyyy-MM-dd");
                    this.form.loadingDate = dateFormat(new Date(),"yyyy-MM-dd");
                    this.hasItem=false;

                }

                this.$refs.modal_1.show();
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            handleDelete() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(this.ids);
                    })
                    .then(() => {
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$refs.crud.toggleSelection();
                    });
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            opened() {
                console.log("opened")
            },
            closed() {
                this.$emit("success");
            }
        }
    };
</script>

<style>
    /*.addPadding {*/
    /*padding: 20px !important;*/
    /*}*/
</style>
